//
//  YXDownloader.m
//  MockProject
//
//  Created by 周丽丽 on 16/8/29.
//  Copyright © 2016年 niuzhaowang. All rights reserved.
//

#import "YXDownloader.h"
#import "YXTaskListModel.h"
@interface YXDownloader ()<ASIProgressDelegate>
@property (nonatomic, strong) ASIHTTPRequest<Ignore> *request;
@end
@implementation YXDownloader
+ (instancetype)downloader{
    YXDownloader *instance = [[self alloc]init];
    instance.state =  TaskStateNotStart;
    return instance;
}
#pragma mark - Download operation
- (void)startDownload{
    self.state = TaskStateDownloading;
    [self setupDownloadSpeed];
    self.request = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:self.urlStr]];
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *folderPath = [path stringByAppendingPathComponent:@"temp"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
    if (!fileExists) {
        [fileManager createDirectoryAtPath:folderPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    NSString *savePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.MP4",self.title]];
    NSString *tempPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"temp/%@.zip.temp",self.title]];
    [self.request setDownloadDestinationPath:savePath];
    [self.request setTemporaryFileDownloadPath:tempPath];
    self.request.shouldContinueWhenAppEntersBackground = YES;
    self.request.allowResumeForFileDownloads = YES;
    [self.request setDownloadProgressDelegate:self];
    self.request.delegate = self;
    [self.request setDidReceiveResponseHeadersSelector:@selector(responseHeadersSize:)];
    [self.request startAsynchronous];
}
- (void)pauseDownload{
    self.state = TaskStatePause;
    self.speed = @"0KB/S";
    [self.request clearDelegatesAndCancel];
}
- (void)resumeDownload{
    self.state = TaskStateResume;
}
- (void)setTaskModel:(YXTaskListModel *)taskModel{
    _taskModel = taskModel;
    self.urlStr = taskModel.taskUrl;
    self.title = taskModel.taskTitle;
}
#pragma mark-ASIProgressDelegate
- (void)setProgress:(float)newProgress{
    self.downloadProgress = newProgress;
    self.downloadSize = self.downloadProgress * self.totalSize;
    [self setupDownloadSpeed];
}
#pragma mark -ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    self.state = TaskStateComplete;
}
-(void)requestFailed:(ASIHTTPRequest *)request
{
    self.state = TaskStateFialed;
    self.speed = @"0KB/S";
}
- (void)responseHeadersSize:(ASIHTTPRequest *)request
{
    NSNumber *size = [request.responseHeaders valueForKey:@"Content-Length"];
   self.totalSize = roundf(size.floatValue/1000.0/1000 * 10)/10;
}
- (void)setupDownloadSpeed{
    float speed = [ASIHTTPRequest averageBandwidthUsedPerSecond]/1024.0;
    if (speed < 999) {
        self.speed = [NSString stringWithFormat:@"%.fKB/S",speed];
    }else if (speed >= 999) {
        speed = speed/1024.0;
        self.speed = [NSString stringWithFormat:@"%.1fM/S",speed];
    }
}
@end
